import { DailogModel } from "@/type/BaseType"
import { ref, reactive, onMounted, nextTick } from "vue"
import { assignRoleSaveApi, getRoleIdApi, getRoleListApi } from '@/api/user/user'
import { AssignRoleListParam } from "@/api/user/userModel"
import { StatusCode } from "@/http/request"
import { getUserId } from "@/utils/auth"
import userInstance from '@/hooks/userInstance'

export default function assignRole(dailog:DailogModel,onShow,onclose) {
    // 全局属性
    const {global} = userInstance()
    // 表格高度
    const tableHeight = ref(0)
    // 被分配角色的用户id
    const selectUserId = ref<string | number>('')
    // 选中角色的id
    const selectRoleId = ref('')
    // 确定
    const confirm = async () => {
        // 新账号在没有分配角色的情况下，要提示分配角色处理
        if(!selectRoleId.value) {
            global.$message({
                message: '请选择角色',
                type: 'warning'
            })
            return
        }
        let params = {
            userId: selectUserId.value,
            roleId: selectRoleId.value
        }
        console.log(params)
        let res = await assignRoleSaveApi(params)
        if(res && res.code === StatusCode.Success) {
            global.$message({
                message: '分配成功',
                type: 'success'
            })
            // 关闭弹窗
            onclose()
            // getRoleList()
        }
    }
    // 展示弹框
    const show = async (name: string, userId: string | number) => {
        selectUserId.value = userId
        selectRoleId.value = ''
        // 查询该用户原来的角色id
        let res = await getRoleIdApi(userId)
        if(res && res.data) {
            selectRoleId.value = res.data.roleId
        }
        // 设置弹框标题
        dailog.title = `为【${name}】分配角色`
        onShow()
    }
    // 角色列表查询参数
    const roleQuery =  reactive<AssignRoleListParam>({
        currentPage: 1,
        pageSize: 4,
        userId: getUserId() || '',
        total: 0
    })

    // 角色列表数据
    const roleList = reactive({
        list: []
    })
    // 获取列表的数据
    const getRoleList = async () => {
        let res = await getRoleListApi(roleQuery)
        if(res && res.code === StatusCode.Success) {
            roleList.list = res.data.records
            roleQuery.total = res.data.total
            // console.log(roleList.list)
        }
    }
    // 页面改变时触发
    const sizeChange = (size: number) => {
        roleQuery.pageSize = size
        getRoleList()
    }
    // 页数改变时触发
    const currentChange = (page: number) => {
        roleQuery.currentPage = page
        getRoleList()
    }  
    // 单选按钮点击事件
    const getSelectRole = (id) => {
        console.log(id)
        selectRoleId.value = id
    }
    onMounted(() => {
        nextTick(() => {
            tableHeight.value = window.innerHeight - 460
        })
        getRoleList()
    })
    return {
        confirm,
        show,
        roleList,
        roleQuery,
        sizeChange,
        currentChange,
        tableHeight,
        selectRoleId,
        getSelectRole
    }
}